<template>
  <div class="read_container">
    <div class="tab_container">
      <van-tabs v-model:active="active" @click-tab="onClickTab">
        <van-tab
          v-for="(item, index) in tabList"
          :title="item.label"
          :name="item.value"
          :key="index"
        ></van-tab>
      </van-tabs>
    </div>
    <div class="type_container" v-if="pageForm.state == '1'">
      <div class="type_list">
        <div
          class="type_item"
          @click="tempItem(null)"
          :class="{ activeType: pageForm.templaterId == null }"
        >
          全部日志
        </div>
        <div
          class="type_item"
          v-for="(item, index) in tempLogList"
          :key="index"
          @click="tempItem(item.id)"
          :class="{ activeType: item.id == pageForm.templaterId }"
        >
          {{ item.name }}
        </div>
      </div>
      <!-- <div class="check">
        <van-checkbox v-model="unread" icon-size="16px" @change="unreadChange"
          >只看未读</van-checkbox
        >
      </div> -->
    </div>
    <div class="content_container">
      <div class="item_box" v-for="(item, index) in logList" :key="index">
        <div class="li_time">{{ item[0].date }}</div>
        <div
          class="li_content"
          v-for="(it, i) in item"
          :key="i"
          @click="itemClick(it)"
        >
          <div class="li_title">
            <img :src="it.img" alt="" />
            <div class="title_box">
              <div class="title">{{ it.userName }}的{{ it.templateName }}</div>
              <div class="time">{{ it.updateTime }}</div>
            </div>
          </div>
          <div class="li_info">
            <div
              class="item_li"
              v-for="(li, j) in it.fields.slice(0, 2)"
              :key="j"
            >
              {{ li.key }}：{{ li.content }}
            </div>
          </div>
          <div class="li_data">
            <div class="li_da">
              <!-- 已读 -->
              <div class="read_num">
                <!-- 
                  --p：这个变量将定义百分比值（不带%符号）。
                  --b：这个变量将定义边框的粗细。
                  --c：这个变量将定义主要颜色。
                -->
                <div
                  class="pie"
                  style="--b: 10px; --c: #576793"
                  :style="{ '--p': it.percent }"
                ></div>
                <div class="num" @click.stop="showReadNum(it.id)">
                  {{ it.readCount || 0 }}人已读
                </div>
              </div>
              <div class="review">
                <van-icon name="chat-o" size="0.5rem" />
                <div class="text">
                  <span v-if="it.readCount">{{ it.commentCount }}人</span>评论
                </div>
              </div>
              <div class="upvote">
                <van-icon name="good-job" size="0.5rem" v-if="it.goodCount" />
                <van-icon name="good-job-o" size="0.5rem" v-else />
                <div class="text">
                  <span v-if="it.goodCount">{{ it.goodCount }}人</span>点赞
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
      <div class="loading" v-if="loading">
        <van-loading vertical color="#0094ff" text-color="#0094ff"
          >加载中...</van-loading
        >
      </div>
      <div class="more_container" v-if="moreFlag" @click="load()">
        <div v-if="loading">
          <van-loading
            type="spinner"
            size="0.5rem"
            color="#308bde"
            style="margin-left: 10px"
            >加载中</van-loading
          >
        </div>
        <div
          style="display: flex; align-items: center"
          v-if="!loading && logList.length"
        >
          <div>加载更多</div>
          <van-icon name="arrow-down" style="margin-left: 5px" />
        </div>
      </div>
      <div class="more_container" style="color: #8d8d8d" v-else>
        <div>暂无更多数据</div>
        <van-icon name="warning-o" style="margin-left: 5px" />
      </div>
    </div>
    <!-- 已读未读弹框 -->
    <van-dialog
      v-model:show="readFlag"
      :showConfirmButton="false"
      :closeOnClickOverlay="true"
    >
      <!-- title -->
      <div class="navbar">
        <div class="options">
          <div
            class="option"
            :class="{ option_active: currentReadIndex == 1 }"
            @click="readClick(1)"
          >
            <div class="text">已读</div>
          </div>
          <div
            class="option mr10"
            :class="{ option_active: currentReadIndex == 0 }"
            @click="readClick(0)"
          >
            <div class="text">未读</div>
          </div>
        </div>
        <div class="close">
          <van-icon name="cross" @click="readFlag = false" />
        </div>
      </div>

      <!-- 列表已读未读 -->
      <div class="read_list">
        <div class="read_item" v-for="item in readList">
          <div>
            <van-image
              radius="0.2rem"
              width="45"
              height="45"
              :src="item.userImg"
              alt=""
            />
          </div>
          <div class="name">{{ item.userName }}</div>
        </div>
      </div>
    </van-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted } from "vue";
import { useRouter } from "vue-router";
import { GetPageList, GetReadList, GetTemplateList } from "@/api/log";
import { Local } from "@/utils/storage";
import { Toast } from 'vant';
onMounted(() => {
  active.value = localStorage.getItem("readLogTab") ? localStorage.getItem("readLogTab") : "1";
  pageForm.value.state = localStorage.getItem("readLogTab") ? localStorage.getItem("readLogTab") : "1";
  if (userId.value) {
    getList();
    getTemplateList();
  }
});
const userId = ref("");
userId.value = Local.get("userId");
const router = useRouter();
const active = ref("");
const tabList = ref([
  {
    label: "我收到的",
    value: "1",
  },
  {
    label: "我发出的",
    value: "2",
  },
  {
    label: "定时发送",
    value: "3",
  },
]);

//点击日志状态
const onClickTab = (e) => {
  tempList = [];
  pageForm.value.pageIndex = 1;
  pageForm.value.state = e.name;
  active.value = e.name;
  localStorage.setItem("readLogTab", active.value);
  getList();
};
//筛选列表项
const tempLogList = ref([]);
const getTemplateList = async () => {
  const res = await GetTemplateList({ userId: userId.value });
  tempLogList.value = res.data;
};
const tempItem = (item) => {
  pageForm.value.templaterId = item;
  pageForm.value.pageIndex = 1;
  tempList = [];
  getList();
};
//日志列表
const logList = ref([]);
const templateNameLogList = ref([]);
const pageForm = ref({
  userId: userId.value,
  pageIndex: 1,
  pageSize: 30,
  state: 1,
  templaterId: null,
});
let tempList = [];
const getList = async () => {
  loading.value = true;
  const res = await GetPageList(pageForm.value);
  loading.value = false;
  let items = res.data.items;
  items.forEach((item) => {
    item.fields.forEach((it) => {
      it.content = JSON.parse(it.content);
      it.value = JSON.parse(it.value);
    });
    item["date"] = item.updateTime.split(" ")[0];
    item["percent"] = (item.readCount / item.sendCount) * 100 + "";
  });
  tempList = tempList.concat(items);
  logList.value = groupBy(tempList, "date");
  templateNameLogList.value = groupBy(tempList, "templateName");
  if (items.length < pageForm.value.pageSize) {
    moreFlag.value = false;
  } else {
    moreFlag.value = true;
  }
};
const groupBy = (list, type) => {
  const groups = {};
  list.forEach((element) => {
    const group = element[type];
    groups[group] = groups[group] || [];
    groups[group].push(element);
  });
  return Object.values(groups);
};
//已读/未读
const readFlag = ref(false);
const readList = ref([]);
const currentReadIndex = ref(0);
const itemId = ref(0);
const showReadNum = (id) => {
  itemId.value = id;
  readFlag.value = true;
  // 重置到已读
  currentReadIndex.value = 1;
  getReadList(currentReadIndex.value);
};
const readClick = (num) => {
  currentReadIndex.value = num;
  getReadList();
};
const getReadList = async () => {
  let req = {
    id: itemId.value,
    state: Number(currentReadIndex.value),
  };
  const res = await GetReadList(req);
  readList.value = res.data ? res.data : [];
};
//加载更多
const moreFlag = ref(true);
const loading = ref(false);
const load = () => {
  pageForm.value.pageIndex++;
  getList();
};
//查看详情
const itemClick = (it) => {
  if (active.value == 3) {
    if(it.isModify){
      Toast.fail('该日志模板已被管理员设置为不可更改');
    }else{
      router.push({ name: "writeLog", query: { detailId: it.id } });
    }
  } else {
    router.push({ name: "readLogInfo", query: { id: it.id } });
  }
};
</script>
<style lang="scss" scoped>
.read_container {
  width: 100%;
  height: 100%;
  .tab_container {
    display: flex;
    justify-content: space-around;
    align-items: center;
    .van-tabs {
      width: 100%;
      :deep(.van-tabs__wrap .van-tabs__nav--line .van-tabs__line) {
        background: #000;
      }
    }
  }
  .type_container {
    width: 100%;
    height: 40px;
    display: flex;
    align-items: center;
    padding: 0 0.3rem;
    box-sizing: border-box;
    background-color: #fff;
    .type_list {
      flex: 1;
      display: flex;
      overflow-x: scroll;
      padding-right: 5px;
      box-sizing: border-box;
      .type_item {
        padding: 5px;
        box-sizing: border-box;
        background-color: #ecedef;
        border-radius: 3px;
        font-size: 0.3rem;
        text-align: center;
        margin-right: 5px;
        display: flex;
        white-space: nowrap;
        cursor: pointer;
      }
      .activeType {
        background-color: #308bde;
        color: #fff;
      }
    }
    .check {
      font-size: 0.4rem;
      display: flex;
      align-items: center;
      margin-left: 10px;
    }
  }
  .content_container {
    width: 100%;
    height: 100%;
    padding-bottom: 60px;
    box-sizing: border-box;
    overflow-y: scroll;
    position: relative;
    .item_box {
      margin-top: 10px;
      .li_time {
        font-size: 0.4rem;
        color: #aaaab3;
        padding: 10px 20px;
        box-sizing: border-box;
      }
      .li_content {
        padding: 20px;
        box-sizing: border-box;
        background-color: #fff;
        cursor: pointer;
        margin-top: 5px;
        .li_title {
          display: flex;
          align-items: center;
          img {
            width: 0.8rem;
            height: 0.8rem;
            border-radius: 5px;
          }
          .title_box {
            margin-left: 10px;
            .title {
              font-size: 0.5rem;
              font-weight: bold;
            }
            .time {
              font-size: 0.3rem;
              color: #aaaab3;
            }
          }
        }
        .li_info {
          font-size: 0.4rem;
          margin-top: 10px;
          color: #8d8d8d;
          .item_li {
            line-height: 24px;
            overflow: hidden;
            text-overflow: ellipsis;
            display: -webkit-box;
            -webkit-line-clamp: 2;
            -webkit-box-orient: vertical;
          }
        }
        .li_data {
          display: flex;
          align-items: center;
          margin-top: 5px;
          .li_da {
            display: flex;
            align-items: center;
            font-size: 12px;
            color: #576793;
            .read_num {
              box-sizing: border-box;
              display: flex;
              align-items: center;
              .pie {
                --w: 12px;
                width: var(--w);
                aspect-ratio: 1;
                display: inline-grid;
                place-content: center;
                margin: 5px;
                margin-left: 0;
                position: relative;
                border: 1px solid #576793;
                border-radius: 50%;
              }
              .pie:before {
                content: "";
                position: absolute;
                border-radius: 50%;
                inset: 0;
                background: conic-gradient(
                  var(--c) calc(var(--p) * 1%),
                  #0000 0
                );
              }
            }
            .review {
              display: flex;
              align-items: center;
              margin: 0 10px;
              .text {
                margin-left: 2px;
              }
            }
            .upvote {
              display: flex;
              align-items: center;
              .text {
                margin-left: 2px;
              }
            }
          }
        }
      }
    }
    .loading {
      position: absolute;
      left: 50%;
      top: 50%;
      transform: translate(-50%, -50%);
    }
    .more_container {
      margin-top: 20px;
      font-size: 0.4rem;
      width: 100%;
      cursor: pointer;
      color: #308bde;
      display: flex;
      justify-content: center;
      align-items: center;
    }
  }
  .navbar {
    display: flex;
    align-items: center;
    justify-content: space-between;
    width: 100%;
    height: 40px;
    padding-left: 20px;
    box-sizing: border-box;
    border-bottom: 1px solid #f3f3f3;
    .options {
      display: flex;
      .mr10 {
        margin: 0 10px;
      }
    }
    .option {
      width: 60px;
      height: 100%;
      line-height: 35px;
      padding-top: 5px;
      color: #acacac;
      font-size: 12px;
      cursor: pointer;
      .text {
        text-align: center;
      }
    }
    .option_active {
      color: #308bde;
      border-bottom: 3px solid #308bde;
    }
    .close {
      margin-right: 15px;
    }
  }
  .read_list {
    padding: 10px 20px 30px 20px;
    box-sizing: border-box;
    display: flex;
    flex-wrap: wrap;
    .read_item {
      display: flex;
      flex-direction: column;
      align-items: center;
      font-size: 12px;
      margin: 5px;
    }
  }
}
</style>
